Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets   = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)


# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0
In [5]:
human_files[:5]
Out[5]:
array(['lfw/Muhammad_Ali/Muhammad_Ali_0001.jpg',
       'lfw/Yoko_Ono/Yoko_Ono_0001.jpg',
       'lfw/Svetlana_Belousova/Svetlana_Belousova_0001.jpg',
       'lfw/Lauren_Hutton/Lauren_Hutton_0001.jpg',
       'lfw/Jennifer_Capriati/Jennifer_Capriati_0005.jpg'], 
      dtype='<U84')
In [6]:
train_files[:5]
Out[6]:
array(['dogImages/train/095.Kuvasz/Kuvasz_06442.jpg',
       'dogImages/train/057.Dalmatian/Dalmatian_04054.jpg',
       'dogImages/train/088.Irish_water_spaniel/Irish_water_spaniel_06014.jpg',
       'dogImages/train/008.American_staffordshire_terrier/American_staffordshire_terrier_00596.jpg',
       'dogImages/train/008.American_staffordshire_terrier/American_staffordshire_terrier_00563.jpg'], 
      dtype='<U99')

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

The algorithm found:

  • 98% Human faces in the 100 Human Faces files
  • 11% Human faces in the 100 Dog images files
In [8]:
human_files_short = human_files[:100]
dog_files_short   = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.

num_humans = 0
num_dogs = 0

for h in human_files_short:
    if face_detector(h):
        num_humans += 1
        
for d in dog_files_short:
    if face_detector(d):
        num_dogs += 1

print('Found {}% Human faces'.format(num_humans))
print('Found {}% Dog faces'.format(num_dogs))
Found 98% Human faces
Found 11% Dog faces

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

Given the state of the art today, we shouldn't expect the user to present only a clear human face; many algorithms on embedded platforms (such as a smartphone) do a stellar job of face recognition, so it is unreasonable to expect users to give up this sophistication.

To detect human faces that are not clearly presented, the face detection algorithm should support partially occluded faces; this approach can introduce its own false positives, so there is some downside to it.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [9]:
def detect_face(img_path, cascade):
    ''' Alternate implementation of Face Detector - using given Haar Cascade file
        :img_path - path to image file
        :cascade - cascade algo to use
        :returns - True if face found, else False
    '''
    img = cv2.imread(img_path)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = cascade.detectMultiScale(img_gray)
    return len(faces) > 0
In [10]:
## Downloaded these two cascade files from OpenCV.org 's Github
CASCADE_ALT2 = 'haarcascades/haarcascade_frontalface_alt2.xml'
CASCADE_TREE = 'haarcascades/haarcascade_frontalface_alt_tree.xml'
In [12]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

## Our data files
human_files_short = human_files[:100]
dog_files_short   = train_files[:100]

## Cascade classifiers
CLF_CASCADE_ALT2 = cv2.CascadeClassifier(CASCADE_ALT2)
CLF_CASCADE_TREE = cv2.CascadeClassifier(CASCADE_TREE)

# counters
humans_alt2, humans_tree = 0, 0
dogs_alt2, dogs_tree     = 0, 0

# let's find humans
print('Looking at humans dataset...')
for h in human_files_short:
    if detect_face(h, CLF_CASCADE_ALT2):
        humans_alt2 += 1
    if detect_face(h, CLF_CASCADE_TREE):
        humans_tree += 1

print('Looking at dogs dataset...')
for d in dog_files_short:
    if detect_face(d, CLF_CASCADE_ALT2):
        dogs_alt2 += 1
    if detect_face(d, CLF_CASCADE_TREE):
        dogs_tree += 1

# results
print('Using ALT2 Cascade, found {}% Human faces'.format(humans_alt2))
print('Using ALT2 Cascade, found {}% Dog faces'.format(dogs_alt2))
print()
print('Using ALT_TREE Cascade, found {}% Human faces'.format(humans_tree))
print('Using ALT_TREE Cascade, found {}% Dog faces'.format(dogs_tree))
Looking at humans dataset...
Looking at dogs dataset...
Using ALT2 Cascade, found 99% Human faces
Using ALT2 Cascade, found 20% Dog faces

Using ALT_TREE Cascade, found 50% Human faces
Using ALT_TREE Cascade, found 1% Dog faces

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [13]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [14]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path, height=224, width=224):
    ''' Loads RGB image as PIL.Image.Image type of given Height x Width dimensions
    '''
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(height, width))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [15]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [16]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

Using the ResNet-50 model, we found:

  • In Humans dataset, 1% were detected as dogs
  • In Dogs dataset, 100% were detected as dogs
In [17]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

humans, dogs = 0, 0

print('Looking for dogs in Humans dataset..')
for h in human_files_short:
    if dog_detector(h):
        humans += 1
print('Looking for dogs in Dogs dataset...')
for d in dog_files_short:
    if dog_detector(d):
        dogs +=1
print('In Humans dataset, found {}% dogs'.format(humans))
print('In Dogs dataset, found {}% dogs'.format(dogs))
Looking for dogs in Humans dataset..
Looking for dogs in Dogs dataset...
In Humans dataset, found 1% dogs
In Dogs dataset, found 100% dogs

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [18]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors  = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [02:17<00:00, 48.58it/s]
100%|██████████| 835/835 [00:15<00:00, 53.52it/s]
100%|██████████| 836/836 [00:15<00:00, 54.79it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

For my model from scratch, I used a simple model used in the CIFAR-10 classification, and modified it a little bit.

It uses 3 convolution layers, each followed by a MaxPool layer, then finally a Dense layer with dropout. Trained using SGD optimizer for about 8 epochs, it results in about 7.75% accuracy on the test set.

Knowing fully well that a random test would yield ~1% accuracy, this model performs better than chance. However, it is nowhere near the accuracy one would want.

A more accurate model is implemented below using transfer learning.

In [19]:
## Show history

def show_history_graph(history):
    '''  Graphically show the history of model fitting
    '''
    
    plt.figure(figsize=(8,8))
    plt.subplot(221)
    # summarize history for accuracy
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    
    # summarize history for loss
    plt.subplot(222)
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    
    plt.tight_layout()
    plt.show() 
In [20]:
from keras.preprocessing.image import ImageDataGenerator

# create and configure augmented image generator
datagen_train = ImageDataGenerator(
    width_shift_range=0.1,  # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,  # randomly shift images vertically (10% of total height)
    horizontal_flip=True,   # randomly flip images horizontally
    rotation_range=25,  # degrees
    # featurewise_std_normalization=True
) 

# create and configure augmented image generator
datagen_valid = ImageDataGenerator(
    width_shift_range=0.1,  # randomly shift images horizontally (10% of total width)
    height_shift_range=0.1,  # randomly shift images vertically (10% of total height)
    horizontal_flip=True,  # randomly flip images horizontally
    rotation_range=25,
    # featurewise_std_normalization=True
)

# fit augmented image generator on data
datagen_train.fit(train_tensors)
datagen_valid.fit(valid_tensors)
In [32]:
### Define our Scratch Model 
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

from keras import backend as K

from keras.callbacks import ModelCheckpoint

NUM_CLASSES = 133  ## Total number of Dog Breeds to classify

K.clear_session()
scratch_model = Sequential()

### TODO: Define your architecture.

INPUT_SHAPE = (224, 224, 3)   # H x W x C for ResNet

scratch_model.add(Conv2D(filters=16, kernel_size=2, padding='valid', activation='relu', 
                        input_shape=INPUT_SHAPE))
scratch_model.add(MaxPooling2D(pool_size=2))
scratch_model.add(Conv2D(filters=32, kernel_size=2, padding='valid', activation='relu'))
scratch_model.add(MaxPooling2D(pool_size=2))
scratch_model.add(Conv2D(filters=64, kernel_size=2, padding='valid', activation='relu'))
scratch_model.add(MaxPooling2D(pool_size=2))

#scratch_model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
#scratch_model.add(MaxPooling2D(pool_size=2))

scratch_model.add(Dropout(0.5))
scratch_model.add(Flatten())
scratch_model.add(Dense(256, activation='relu'))
scratch_model.add(Dropout(0.4))
scratch_model.add(Dense(NUM_CLASSES, activation='softmax'))


scratch_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 223, 223, 16)      208       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 111, 111, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 110, 110, 32)      2080      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 55, 55, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 54, 54, 64)        8256      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 27, 27, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 27, 27, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 46656)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 256)               11944192  
_________________________________________________________________
dropout_2 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               34181     
=================================================================
Total params: 11,988,917.0
Trainable params: 11,988,917.0
Non-trainable params: 0.0
_________________________________________________________________
In [ ]:
 
In [ ]:
 
In [ ]:
 

Compile the Model

In [39]:
scratch_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [40]:
from keras.callbacks import ModelCheckpoint 
from keras.callbacks import ReduceLROnPlateau

### TODO: specify the number of epochs that you would like to use to train the model.

BATCH_SIZE = 32
epochs = 8

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

# reduce LR
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                              patience=3, min_lr=0.0005, verbose=1)

augment_data = False   # change to True as needed

if not augment_data:

    print('Training... without data augmentation')
    history = scratch_model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, 
          batch_size=BATCH_SIZE, 
          callbacks=[checkpointer], 
          verbose=1)

else:
    print('Training... WITH data augmentation')
    history = scratch_model.fit_generator(datagen_train.flow(train_tensors, train_targets, batch_size=BATCH_SIZE),
                    steps_per_epoch=train_tensors.shape[0] // BATCH_SIZE,
                    epochs=epochs, 
                    verbose=2, 
                    callbacks=[checkpointer],
                    validation_data=datagen_valid.flow(valid_tensors, valid_targets, batch_size=BATCH_SIZE),
                    validation_steps=valid_tensors.shape[0] // BATCH_SIZE)

print('Done training')
show_history_graph(history)
Training... without data augmentation
Train on 6680 samples, validate on 835 samples
Epoch 1/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.8982 - acc: 0.1262  Epoch 00000: val_loss improved from inf to 4.32641, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 179s - loss: 3.8992 - acc: 0.1262 - val_loss: 4.3264 - val_acc: 0.0647
Epoch 2/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.5987 - acc: 0.1642  Epoch 00001: val_loss improved from 4.32641 to 4.24722, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 177s - loss: 3.5978 - acc: 0.1647 - val_loss: 4.2472 - val_acc: 0.0802
Epoch 3/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.4582 - acc: 0.1895  Epoch 00002: val_loss did not improve
6680/6680 [==============================] - 177s - loss: 3.4576 - acc: 0.1895 - val_loss: 4.2478 - val_acc: 0.0731
Epoch 4/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.4017 - acc: 0.1973  Epoch 00003: val_loss improved from 4.24722 to 4.19701, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 179s - loss: 3.4002 - acc: 0.1975 - val_loss: 4.1970 - val_acc: 0.0850
Epoch 5/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.3109 - acc: 0.2212  Epoch 00004: val_loss improved from 4.19701 to 4.16876, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 179s - loss: 3.3098 - acc: 0.2211 - val_loss: 4.1688 - val_acc: 0.0802
Epoch 6/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.2381 - acc: 0.2249  Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 176s - loss: 3.2369 - acc: 0.2251 - val_loss: 4.3031 - val_acc: 0.0754
Epoch 7/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.1615 - acc: 0.2426  Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 176s - loss: 3.1609 - acc: 0.2425 - val_loss: 4.2858 - val_acc: 0.0778
Epoch 8/8
6656/6680 [============================>.] - ETA: 0s - loss: 3.1080 - acc: 0.2523  Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 176s - loss: 3.1070 - acc: 0.2524 - val_loss: 4.1770 - val_acc: 0.0874
Done training

Load the Model with the Best Validation Loss

In [41]:
scratch_model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [42]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(scratch_model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 7.7751%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [43]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16  = bottleneck_features['test']
In [45]:
print('Train bottleneck features shape:', train_VGG16.shape)
print('Valid bottleneck features shape:', valid_VGG16.shape)
print('Test  bottleneck features shape:', test_VGG16.shape)
Train bottleneck features shape: (6680, 7, 7, 512)
Valid bottleneck features shape: (835, 7, 7, 512)
Test  bottleneck features shape: (836, 7, 7, 512)

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [46]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [47]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [49]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

hist_vgg = VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.5559 - acc: 0.5244Epoch 00000: val_loss improved from inf to 8.21048, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.5273 - acc: 0.5260 - val_loss: 8.2105 - val_acc: 0.4263
Epoch 2/20
6360/6680 [===========================>..] - ETA: 0s - loss: 7.5365 - acc: 0.5269Epoch 00001: val_loss did not improve
6680/6680 [==============================] - 0s - loss: 7.5229 - acc: 0.5274 - val_loss: 8.2173 - val_acc: 0.4419
Epoch 3/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.4879 - acc: 0.5290Epoch 00002: val_loss improved from 8.21048 to 8.18130, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 7.4975 - acc: 0.5283 - val_loss: 8.1813 - val_acc: 0.4395
Epoch 4/20
6320/6680 [===========================>..] - ETA: 0s - loss: 7.4769 - acc: 0.5285Epoch 00003: val_loss improved from 8.18130 to 8.16946, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 7.4627 - acc: 0.5295 - val_loss: 8.1695 - val_acc: 0.4323
Epoch 5/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.3989 - acc: 0.5326Epoch 00004: val_loss improved from 8.16946 to 8.05631, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.3873 - acc: 0.5331 - val_loss: 8.0563 - val_acc: 0.4419
Epoch 6/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.2618 - acc: 0.5391Epoch 00005: val_loss improved from 8.05631 to 7.97818, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 7.2688 - acc: 0.5388 - val_loss: 7.9782 - val_acc: 0.4455
Epoch 7/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.1722 - acc: 0.5457Epoch 00006: val_loss improved from 7.97818 to 7.93362, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 7.1695 - acc: 0.5455 - val_loss: 7.9336 - val_acc: 0.4431
Epoch 8/20
6380/6680 [===========================>..] - ETA: 0s - loss: 7.1048 - acc: 0.5547Epoch 00007: val_loss improved from 7.93362 to 7.85457, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 7.1169 - acc: 0.5539 - val_loss: 7.8546 - val_acc: 0.4527
Epoch 9/20
6360/6680 [===========================>..] - ETA: 0s - loss: 7.1340 - acc: 0.5524Epoch 00008: val_loss improved from 7.85457 to 7.85319, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 7.0964 - acc: 0.5546 - val_loss: 7.8532 - val_acc: 0.4587
Epoch 10/20
6360/6680 [===========================>..] - ETA: 0s - loss: 7.0069 - acc: 0.5571Epoch 00009: val_loss improved from 7.85319 to 7.79109, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 6.9791 - acc: 0.5587 - val_loss: 7.7911 - val_acc: 0.4575
Epoch 11/20
6520/6680 [============================>.] - ETA: 0s - loss: 6.8734 - acc: 0.5606Epoch 00010: val_loss improved from 7.79109 to 7.70499, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.8549 - acc: 0.5617 - val_loss: 7.7050 - val_acc: 0.4611
Epoch 12/20
6460/6680 [============================>.] - ETA: 0s - loss: 6.7211 - acc: 0.5683Epoch 00011: val_loss improved from 7.70499 to 7.58023, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.6838 - acc: 0.5707 - val_loss: 7.5802 - val_acc: 0.4539
Epoch 13/20
6380/6680 [===========================>..] - ETA: 0s - loss: 6.4557 - acc: 0.5829Epoch 00012: val_loss improved from 7.58023 to 7.41971, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 6.4840 - acc: 0.5814 - val_loss: 7.4197 - val_acc: 0.4683
Epoch 14/20
6360/6680 [===========================>..] - ETA: 0s - loss: 6.4566 - acc: 0.5910Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 0s - loss: 6.3982 - acc: 0.5946 - val_loss: 7.4826 - val_acc: 0.4587
Epoch 15/20
6400/6680 [===========================>..] - ETA: 0s - loss: 6.3629 - acc: 0.5972Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 0s - loss: 6.3483 - acc: 0.5982 - val_loss: 7.4655 - val_acc: 0.4611
Epoch 16/20
6540/6680 [============================>.] - ETA: 0s - loss: 6.2099 - acc: 0.6072Epoch 00015: val_loss improved from 7.41971 to 7.22654, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 6.2174 - acc: 0.6069 - val_loss: 7.2265 - val_acc: 0.4778
Epoch 17/20
6340/6680 [===========================>..] - ETA: 0s - loss: 6.2102 - acc: 0.6109Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 0s - loss: 6.1940 - acc: 0.6118 - val_loss: 7.2814 - val_acc: 0.4766
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 6.1808 - acc: 0.6141Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 0s - loss: 6.1861 - acc: 0.6138 - val_loss: 7.3026 - val_acc: 0.4778
Epoch 19/20
6420/6680 [===========================>..] - ETA: 0s - loss: 6.2026 - acc: 0.6115Epoch 00018: val_loss improved from 7.22654 to 7.22390, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 0s - loss: 6.1794 - acc: 0.6129 - val_loss: 7.2239 - val_acc: 0.4934
Epoch 20/20
6480/6680 [============================>.] - ETA: 0s - loss: 6.1044 - acc: 0.6136Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 0s - loss: 6.0922 - acc: 0.6141 - val_loss: 7.2638 - val_acc: 0.4647
In [50]:
show_history_graph(hist_vgg)

Load the Model with the Best Validation Loss

In [51]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [52]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 48.2057%

Results - about 48.2% accuracy

Predict Dog Breed with the Model

In [53]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [55]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

INCEPTION_BNECK = 'bottleneck_features/DogInceptionV3Data.npz'

bottleneck_features = np.load(INCEPTION_BNECK)
train_incp_bn = bottleneck_features['train']
valid_incp_bn = bottleneck_features['valid']
test_incp_bn  = bottleneck_features['test']
In [56]:
print('Train bottleneck size {:,}, shape: {}'.format(train_incp_bn.size, train_incp_bn.shape))
print('Valid bottleneck size {:,}, shape: {}'.format(valid_incp_bn.size, valid_incp_bn.shape))
print('Test  bottleneck size {:,}, shape: {}'.format(test_incp_bn.size, test_incp_bn.shape))
Train bottleneck size 342,016,000, shape: (6680, 5, 5, 2048)
Valid bottleneck size 42,752,000, shape: (835, 5, 5, 2048)
Test  bottleneck size 42,803,200, shape: (836, 5, 5, 2048)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

I used the Inception V3 architecture for transfer learning. I added two more Dense layers on top, with Dropout, and experimented with the various combinations of layers, dropouts, epoch sizes, optimizers and achieved results ranging from 77% accuracy to 82% accuracy. The following table shows a sample table of models with their results, each run up to 20 epochs, with batch_size of 16:

Note that GAP refers to Global Average Pooling layer with input shape 5x5x2048 (run thru the bottleneck)

Comparison Model Model Model Model
Name Model-1 Model-2 Model-3 Model-4
Layer1 GAP GAP GAP GAP
L2 Dense-1024, 50% drop Dense-512, 50% drop Dense-512, 30% drop Dense-512, 50% drop
L3 Dense-512, 50% drop Dense-256, 50% drop Dense-384, 30% drop Dense-512, 50% drop
L4 N/A N/A Dense-256, 30% drop Dense-512, 30% drop
Optim Adam Adam Adam Adam
LR(min) 0.0005 0.0005 0.0001 0.001
Accuracy 80.3% 78.2% 78.67% 78.8%

I finally settled on the following architecture:

  • Input layer (with bottleneck features)
  • Dense layer with 1024 nodes, with 50% Dropout
  • Dense layer with 512 nodes, with 50% Droput
  • Adam optimizer
  • Trained on 20 epochs, with batch_size 16

This achieved 82.2% accuracy on the test set.

In [58]:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Activation
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.pooling import GlobalAveragePooling2D

from keras.callbacks import ModelCheckpoint  
from keras.preprocessing.image import ImageDataGenerator
In [59]:
#### Define our Model #####

### TODO: Define your architecture.

K.clear_session()

## Define our extension to the InceptionV3 model
inception_bneck = Sequential()
# input shape is M x 5 x 5 x 2048
inception_bneck.add(GlobalAveragePooling2D(input_shape=train_incp_bn.shape[1:]))
inception_bneck.add(Activation('relu'))
inception_bneck.add(Dense(1024, activation='relu'))
inception_bneck.add(Dropout(0.5))
inception_bneck.add(Dense(512, activation='relu'))
inception_bneck.add(Dropout(0.5))
inception_bneck.add(Dense(NUM_CLASSES, activation='softmax'))

inception_bneck.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 2048)              0         
_________________________________________________________________
activation_1 (Activation)    (None, 2048)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 1024)              2098176   
_________________________________________________________________
dropout_1 (Dropout)          (None, 1024)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 512)               524800    
_________________________________________________________________
dropout_2 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 2,691,205.0
Trainable params: 2,691,205.0
Non-trainable params: 0.0
_________________________________________________________________
In [ ]:
 

(IMPLEMENTATION) Compile the Model

In [60]:
### TODO: Compile the model.

inception_bneck.compile(optimizer='adam',
                        loss='categorical_crossentropy',
                        metrics=['accuracy'])
In [62]:
!ls -l
total 1176
-rw-r--r--   1 aa  staff     187 Jan  4 13:02 CODEOWNERS
-rw-r--r--   1 aa  staff    6214 Jan  4 13:02 README.md
drwxr-xr-x   3 aa  staff     102 Jan  4 20:33 __pycache__
drwxr-xr-x   5 aa  staff     170 Jan  4 16:02 bottleneck_features
lrwxr-xr-x   1 aa  staff      49 Jan  4 16:04 dogImages -> /Users/aa/Developer/datasets/dog_breeds/dogImages
-rw-r--r--   1 aa  staff  576682 Jan  5 09:51 dog_app.ipynb
-rw-r--r--   1 aa  staff     932 Jan  4 13:02 extract_bottleneck_features.py
drwxr-xr-x   5 aa  staff     170 Jan  4 17:06 haarcascades
drwxr-xr-x  12 aa  staff     408 Jan  4 13:02 images
lrwxr-xr-x   1 aa  staff      46 Jan  4 16:05 lfw -> /Users/aa/Developer/datasets/Labeled_Faces/lfw
drwxr-xr-x  10 aa  staff     340 Jan  4 13:02 requirements
drwxr-xr-x   5 aa  staff     170 Jan  4 20:30 saved_models

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [63]:
### TODO: Train the model.

EPOCHS = 20
BATCH_SIZE=16

from keras.callbacks import ReduceLROnPlateau

# checkpoint file
inception_ckpoint_file = 'saved_models/inceptionv3_bneck.weights.hdf5'
## callbacks
checkpointer = ModelCheckpoint(filepath=inception_ckpoint_file, 
                               verbose=1, save_best_only=True)


# reduce LR
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                              patience=5, min_lr=0.0005, verbose=1)

print('Starting training...')
hist = inception_bneck.fit(train_incp_bn, train_targets,
                          validation_data=(valid_incp_bn, valid_targets),
                          epochs=EPOCHS,
                          batch_size=BATCH_SIZE,
                          callbacks=[checkpointer, reduce_lr],
                          verbose=1)
print('Training done.')
# plot the history
show_history_graph(hist)
Starting training...
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6672/6680 [============================>.] - ETA: 0s - loss: 2.8431 - acc: 0.3693  Epoch 00000: val_loss improved from inf to 0.96581, saving model to saved_models/inceptionv3_bneck.weights.hdf5
6680/6680 [==============================] - 20s - loss: 2.8412 - acc: 0.3696 - val_loss: 0.9658 - val_acc: 0.7222
Epoch 2/20
6672/6680 [============================>.] - ETA: 0s - loss: 1.5184 - acc: 0.6046 Epoch 00001: val_loss improved from 0.96581 to 0.77064, saving model to saved_models/inceptionv3_bneck.weights.hdf5
6680/6680 [==============================] - 15s - loss: 1.5183 - acc: 0.6045 - val_loss: 0.7706 - val_acc: 0.7653
Epoch 3/20
6672/6680 [============================>.] - ETA: 0s - loss: 1.2615 - acc: 0.6637 Epoch 00002: val_loss improved from 0.77064 to 0.67314, saving model to saved_models/inceptionv3_bneck.weights.hdf5
6680/6680 [==============================] - 14s - loss: 1.2606 - acc: 0.6638 - val_loss: 0.6731 - val_acc: 0.7976
Epoch 4/20
6672/6680 [============================>.] - ETA: 0s - loss: 1.1782 - acc: 0.6878 Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 1.1792 - acc: 0.6876 - val_loss: 0.7322 - val_acc: 0.7713
Epoch 5/20
6672/6680 [============================>.] - ETA: 0s - loss: 1.0910 - acc: 0.7092 Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 1.0910 - acc: 0.7093 - val_loss: 0.7154 - val_acc: 0.7928
Epoch 6/20
6672/6680 [============================>.] - ETA: 0s - loss: 1.0202 - acc: 0.7271 Epoch 00005: val_loss improved from 0.67314 to 0.60578, saving model to saved_models/inceptionv3_bneck.weights.hdf5
6680/6680 [==============================] - 14s - loss: 1.0201 - acc: 0.7269 - val_loss: 0.6058 - val_acc: 0.8192
Epoch 7/20
6672/6680 [============================>.] - ETA: 0s - loss: 1.0455 - acc: 0.7220 Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 1.0447 - acc: 0.7220 - val_loss: 0.6981 - val_acc: 0.8048
Epoch 8/20
6656/6680 [============================>.] - ETA: 0s - loss: 0.9591 - acc: 0.7392 Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.9636 - acc: 0.7389 - val_loss: 0.6680 - val_acc: 0.8228
Epoch 9/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.9430 - acc: 0.7452  - ETA: 12s - loss: 0.8425 - acc: 0.7941 - ETA: 7s - loss: 0.9012 - acc: 0.7579 - ETA: 2s - loss: 0.9457 - acc: 0.7447Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.9422 - acc: 0.7454 - val_loss: 0.6304 - val_acc: 0.8228
Epoch 10/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.8992 - acc: 0.7611  - ETA: 1s - loss: 0.9040 - acc: 0.7590Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.9001 - acc: 0.7608 - val_loss: 0.6562 - val_acc: 0.8168
Epoch 11/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.9044 - acc: 0.7600 Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.9043 - acc: 0.7597 - val_loss: 0.6560 - val_acc: 0.8263
Epoch 12/20
6656/6680 [============================>.] - ETA: 0s - loss: 0.8921 - acc: 0.7658 Epoch 00011: val_loss did not improve

Epoch 00011: reducing learning rate to 0.0005.
6680/6680 [==============================] - 15s - loss: 0.8921 - acc: 0.7659 - val_loss: 0.7389 - val_acc: 0.8240
Epoch 13/20
6656/6680 [============================>.] - ETA: 0s - loss: 0.6616 - acc: 0.8140 Epoch 00012: val_loss improved from 0.60578 to 0.59213, saving model to saved_models/inceptionv3_bneck.weights.hdf5
6680/6680 [==============================] - 14s - loss: 0.6622 - acc: 0.8138 - val_loss: 0.5921 - val_acc: 0.8359
Epoch 14/20
6656/6680 [============================>.] - ETA: 0s - loss: 0.5629 - acc: 0.8407 Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.5633 - acc: 0.8404 - val_loss: 0.5930 - val_acc: 0.8383
Epoch 15/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.5128 - acc: 0.8471 Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.5130 - acc: 0.8472 - val_loss: 0.6008 - val_acc: 0.8395
Epoch 16/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.5074 - acc: 0.8476 Epoch 00015: val_loss improved from 0.59213 to 0.58855, saving model to saved_models/inceptionv3_bneck.weights.hdf5
6680/6680 [==============================] - 14s - loss: 0.5071 - acc: 0.8476 - val_loss: 0.5886 - val_acc: 0.8479
Epoch 17/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.4807 - acc: 0.8569 Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.4813 - acc: 0.8566 - val_loss: 0.6086 - val_acc: 0.8383
Epoch 18/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.4802 - acc: 0.8528  - ETA: 10s - loss: 0.4545 - acc: 0.8573Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.4797 - acc: 0.8530 - val_loss: 0.6002 - val_acc: 0.8443
Epoch 19/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.4480 - acc: 0.8665  - ETA: 5s - loss: 0.4495 - acc: 0.8651Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.4483 - acc: 0.8663 - val_loss: 0.6422 - val_acc: 0.8287
Epoch 20/20
6672/6680 [============================>.] - ETA: 0s - loss: 0.4303 - acc: 0.8668 Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 14s - loss: 0.4316 - acc: 0.8666 - val_loss: 0.6278 - val_acc: 0.8443
Training done.

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [64]:
### TODO: Load the model weights with the best validation loss.

## load the best model

inception_bneck.load_weights(inception_ckpoint_file)

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [65]:
### TODO: Calculate classification accuracy on the test dataset.

#### Test the network

# get index of predicted dog breed for each img in test set
predictions = [np.argmax(inception_bneck.predict(np.expand_dims(feature, axis=0)))
              for feature in test_incp_bn]

# test accuracy
test_accuracy = 100. * np.sum(np.array(predictions) == np.argmax(test_targets, axis=1)) / len(predictions)

print('Test accuracy: {:.4f}%'.format(test_accuracy))
Test accuracy: 82.1770%

Results: 82.2% accuracy

In [67]:
### plot some figures we got wrong

fig = plt.figure(figsize=(20, 12))

for i, ix in enumerate(np.random.choice(test_tensors.shape[0], size=24, replace=False)):
    ax = fig.add_subplot(4, 6, i+1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(test_tensors[ix]))
    # correct img ix
    true_index = np.argmax(test_targets[ix])
    # predicted img ix
    pred_index = predictions[ix]
    ax.set_title('{}\n[{}]'.format(dog_names[pred_index], dog_names[true_index]),
                color=('blue' if pred_index == true_index else 'red'))
plt.tight_layout()

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [69]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

# checkpoint file
inception_ckpoint_file = 'saved_models/inceptionv3_bneck.weights.hdf5'

# load weights
inception_bneck.load_weights(inception_ckpoint_file)
In [115]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from keras.applications.inception_v3 import InceptionV3
from keras.applications.inception_v3 import preprocess_input as preprocess_inception_input

def detect_dog_breed(img_path, given_model, use_bottleneck=True, img_H=224, img_W=224):
    ''' Detect dog breed given image in the img_path,
        using given model, using either bottleneck features (or not)
        with given img Height and Width
        
        @return: Dog breed (str)
    '''
    print('Detecting dog breed...')
    tensor = path_to_tensor(img_path, img_H, img_W)
    
    # using given image, extract its bottleneck features by running thru InceptionV3 n/w first
    if use_bottleneck: 
        tensor = extract_InceptionV3(tensor)
    else:
        tensor = preprocess_inception_input(tensor)
    
    # print('  [input tensor shape: {}]'.format(tensor.shape))
    # make predictions (probabilities)
    predicted_vector = given_model.predict(tensor)
    # get max index
    y_hat = np.argmax(predicted_vector)
    chance = 100. * predicted_vector[0][y_hat]  # probability of correctness
    # print('  [y_hat:{}]'.format(y_hat))
    # print('  prob:{:.2f}%'.format(chance))

    # return dog breed and probability 
    return dog_names[y_hat], chance

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [127]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def whose_a_good_doggy(img_path):
    ''' Using the given image (in img_path), returns either:
        - Dog breed (if it's a dog)
        - Dog breed that resembles a human (if it's a human face)
        
        Uses the transfer-learned CNN model from Step 5
    '''
    print('.'*60)
    print('Given image:', img_path)
    
    # human face?
    human_found = face_detector(img_path)
    print('Found human:', human_found)
    
    # doggy ?
    # dog_found   = dog_detector(img_path)
    # print('Found dog:  ', dog_found)
    
    # find breed of dog
    breed, chance = detect_dog_breed(img_path, inception_bneck, use_bottleneck=True, img_H=229, img_W=229)
    print()
    print('Image is dog breed: {} ({:.2f}% prob)'.format(breed, chance))
    print('🐶 Woof!') if not human_found else print('Hellooo, 🐱👩🏻👦🏻👧🏻 animal 🤔')
    print('='*60)
In [121]:
import matplotlib.image as mpimg

def disp_image(img_path):
    img = mpimg.imread(img_path)
    fig = plt.figure()
    plt.subplot()
    plt.imshow(img)
    plt.axis('off')
    plt.plot()
    plt.show()

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

The accuracy of the dog breed classifier is very decent and better than I expected! I also output the certainty of breed classification so we can get some confidence in its abilities. In general, when a dog image is presented, the confidence is pretty high (> 80%), while when a human image is presented the confidence is pretty low (1%-2%), which is reasonable given that a random guess would result in 1/133 or 0.75% accuracy.

I used some extra images of well known celebrities (Obama, etc.) and it's hilarious to see their results. One would expect Trump to resemble a pitbull or some fierce dog breed, but the model predicts him as a Dachshund, with 1.7% confidence. Interestingly, it also predicts Obama as Dachshund with the same confidence. 🤔🤔

To improve the algorithm, further steps can be taken:

  • Data augmentation. I didn't pursue data augmentation here, but it could reasonably add 1%-3% accuracy (or more)
  • Improve human detection, with Haar features
  • Train on a larger dataset, for more epochs. In my case, I only trained on my Macbook Pro, but potentially using a GPU-based hardware with larger dataset, along with data augmentation, for 30-50 epochs might result in much better accuracy.

Overall, this was a fun project!

In [87]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

def detect_image(img_path):
    disp_image(img_path)
    whose_a_good_doggy(img_path)
In [128]:
!ls -lt images
total 1696
-rw-r--r--@ 1 aa  staff   36281 Jan  5 16:22 trump_scorn.jpg
-rw-r--r--@ 1 aa  staff   51536 Jan  5 16:22 eric_trump_2006_04_29.jpg
-rw-r--r--@ 1 aa  staff   11167 Jan  5 16:20 obama_img.jpg
-rw-r--r--  1 aa  staff   41784 Jan  4 13:02 American_water_spaniel_00648.jpg
-rw-r--r--  1 aa  staff   77473 Jan  4 13:02 Brittany_02625.jpg
-rw-r--r--  1 aa  staff   61998 Jan  4 13:02 Curly-coated_retriever_03896.jpg
-rw-r--r--  1 aa  staff   58710 Jan  4 13:02 Labrador_retriever_06449.jpg
-rw-r--r--  1 aa  staff   35774 Jan  4 13:02 Labrador_retriever_06455.jpg
-rw-r--r--  1 aa  staff   52100 Jan  4 13:02 Labrador_retriever_06457.jpg
-rw-r--r--  1 aa  staff   24063 Jan  4 13:02 Welsh_springer_spaniel_08203.jpg
-rw-r--r--  1 aa  staff  185595 Jan  4 13:02 sample_cnn.png
-rw-r--r--  1 aa  staff  125636 Jan  4 13:02 sample_dog_output.png
-rw-r--r--  1 aa  staff   81927 Jan  4 13:02 sample_human_output.png
In [129]:
TEST_IMAGE_DIR = 'images'
test_images = glob(TEST_IMAGE_DIR + '/*')
test_images
Out[129]:
['images/American_water_spaniel_00648.jpg',
 'images/Brittany_02625.jpg',
 'images/Curly-coated_retriever_03896.jpg',
 'images/eric_trump_2006_04_29.jpg',
 'images/Labrador_retriever_06449.jpg',
 'images/Labrador_retriever_06455.jpg',
 'images/Labrador_retriever_06457.jpg',
 'images/obama_img.jpg',
 'images/sample_cnn.png',
 'images/sample_dog_output.png',
 'images/sample_human_output.png',
 'images/trump_scorn.jpg',
 'images/Welsh_springer_spaniel_08203.jpg']
In [136]:
for tst_img in test_images:
    detect_image(tst_img)
............................................................
Given image: images/American_water_spaniel_00648.jpg
Found human: False
Detecting dog breed...

Image is dog breed: American_water_spaniel (63.37% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/Brittany_02625.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Brittany (99.94% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/Curly-coated_retriever_03896.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Curly-coated_retriever (98.18% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/eric_trump_2006_04_29.jpg
Found human: True
Detecting dog breed...

Image is dog breed: Norwegian_buhund (1.32% prob)
Hellooo, 🐱👩🏻👦🏻👧🏻 animal 🤔
============================================================
............................................................
Given image: images/Labrador_retriever_06449.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Labrador_retriever (99.09% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/Labrador_retriever_06455.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Labrador_retriever (78.17% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/Labrador_retriever_06457.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Labrador_retriever (99.44% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/obama_img.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Dachshund (1.84% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/sample_cnn.png
Found human: False
Detecting dog breed...

Image is dog breed: Icelandic_sheepdog (1.56% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/sample_dog_output.png
Found human: False
Detecting dog breed...

Image is dog breed: Bull_terrier (11.64% prob)
🐶 Woof!
============================================================
............................................................
Given image: images/sample_human_output.png
Found human: True
Detecting dog breed...

Image is dog breed: Akita (1.50% prob)
Hellooo, 🐱👩🏻👦🏻👧🏻 animal 🤔
============================================================
............................................................
Given image: images/trump_scorn.jpg
Found human: True
Detecting dog breed...

Image is dog breed: Dachshund (1.72% prob)
Hellooo, 🐱👩🏻👦🏻👧🏻 animal 🤔
============================================================
............................................................
Given image: images/Welsh_springer_spaniel_08203.jpg
Found human: False
Detecting dog breed...

Image is dog breed: Welsh_springer_spaniel (98.21% prob)
🐶 Woof!
============================================================
In [ ]: